<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="8" :md="12" :sm="24">
            <a-form-item label="项目名称">
              <a-input placeholder="请输入项目名称" v-model="queryParam.projectName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="8" :md="12" :sm="24">
            <a-form-item label="客户名称">
              <a-input placeholder="请输入客户名称" v-model="queryParam.customerName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="8" :md="12" :sm="24">
            <a-form-item label="联系人">
              <a-input placeholder="请输入联系人" v-model="queryParam.contactPerson" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="8" :md="12" :sm="24">
            <a-form-item label="项目状态">
              <a-select placeholder="请选择项目状态" v-model="queryParam.status" allowClear>
                <a-select-option :value="0">未开始</a-select-option>
                <a-select-option :value="1">进行中</a-select-option>
                <a-select-option :value="2">已完成</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="12" :lg="12" :md="12" :sm="24">
              <a-form-item label="开始日期">
                <a-range-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  :placeholder="['开始日期', '结束日期']"
                  @change="(dates, dateStrings) => {
                    queryParam.startDate_begin = dateStrings[0];
                    queryParam.startDate_end = dateStrings[1];
                  }"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="12" :lg="12" :md="12" :sm="24">
              <a-form-item label="结束日期">
                <a-range-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  :placeholder="['开始日期', '结束日期']"
                  @change="(dates, dateStrings) => {
                    queryParam.endDate_begin = dateStrings[0];
                    queryParam.endDate_end = dateStrings[1];
                  }"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="项目金额">
                <a-input-number style="width:45%" placeholder="最小值" v-model="queryParam.projectAmount_begin"></a-input-number>
                <span style="display: inline-block; text-align: center; width: 10%">-</span>
                <a-input-number style="width:45%" placeholder="最大值" v-model="queryParam.projectAmount_end"></a-input-number>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="省份">
                <a-select 
                  v-model="queryParam.provinceCode" 
                  placeholder="请选择省份" 
                  @change="provinceChange" 
                  allowClear>
                  <a-select-option v-for="(name, code) in provinceOptions" :key="code" :value="code">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="城市">
                <a-select 
                  v-model="queryParam.cityCode" 
                  placeholder="请选择城市" 
                  @change="cityChange" 
                  :disabled="!queryParam.provinceCode"
                  allowClear>
                  <a-select-option v-for="(name, code) in cityOptions" :key="code" :value="code">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="区县">
                <a-select 
                  v-model="queryParam.areaCode" 
                  placeholder="请选择区县" 
                  :disabled="!queryParam.cityCode"
                  allowClear>
                  <a-select-option v-for="(name, code) in areaOptions" :key="code" :value="code">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="8" :md="12" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" v-if="hasPermission('crm:project:add')">新增项目</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('项目信息')" style="margin-left: 8px" v-if="hasPermission('crm:project:export')">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :beforeUpload="beforeUpload"
        style="display: inline-block; margin-left: 8px"
        v-if="hasPermission('crm:project:import')"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDelete" v-if="hasPermission('crm:project:delete')">
            <a-icon type="delete"/>删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-card :bordered="false" class="card-table">
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          :scroll="{x: 'max-content'}"
          class="j-table-force-nowrap"
          @change="handleTableChange">

          <template slot="statusSlot" slot-scope="text">
            <a-tag v-if="text == 0" color="blue">未开始</a-tag>
            <a-tag v-else-if="text == 1" color="green">进行中</a-tag>
            <a-tag v-else-if="text == 2" color="orange">已完成</a-tag>
          </template>

          <span slot="action" slot-scope="text, record">
            <a @click="handleEdit(record)" v-if="hasPermission('crm:project:edit')">编辑</a>
            <a-divider type="vertical" v-if="hasPermission('crm:project:edit')"/>
            <a @click="handleDetail(record)" v-if="hasPermission('crm:project:detail')">查看</a>
            <a-divider type="vertical" v-if="hasPermission('crm:project:detail')"/>
            <a-dropdown>
              <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item v-if="hasPermission('crm:project:delete')">
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </a-table>
      </a-card>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <project-modal ref="modalForm" @ok="modalFormOk"></project-modal>
    <project-detail-modal ref="detailModal"></project-detail-modal>
  </a-card>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ProjectModal from './modules/ProjectModal'
  import ProjectDetailModal from './modules/ProjectDetailModal'
  import { projectList, projectDelete, projectDeleteBatch } from '@/api/crm'
  import moment from 'moment'
  import '@/assets/less/TableExpand.less'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JAreaLinkage from '@/components/jeecg/JAreaLinkage'

  export default {
    name: "ProjectList",
    mixins: [JeecgListMixin],
    components: {
      ProjectModal,
      ProjectDetailModal,
      JDate,
      JDictSelectTag,
      JAreaLinkage
    },
    created() {
      this.loadProvinceData();
      // 加载权限数据
      this.loadPermissionData();
      // 加载字典数据
      this.initDictConfig()
      
      // 页面加载时重置查询条件
      this.searchReset()
    },
    data() {
      return {
        description: '工程项目管理页面',
        // 省市区数据
        provinceOptions: {},
        cityOptions: {},
        areaOptions: {},
        // 权限数据
        permissionList: [],
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width: 50,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '项目名称',
            align:"center",
            dataIndex: 'projectName',
            width: 180,
            ellipsis: true
          },
          {
            title: '客户名称',
            align:"center",
            dataIndex: 'customerName',
            width: 180,
            ellipsis: true
          },
          {
            title: '联系人',
            align:"center",
            dataIndex: 'contactPerson',
            width: 100
          },
          {
            title: '联系电话',
            align:"center",
            dataIndex: 'contactPhone',
            width: 120
          },
          {
            title: '项目状态',
            align:"center",
            dataIndex: 'status',
            width: 100,
            scopedSlots: { customRender: 'statusSlot' }
          },
          {
            title: '项目金额',
            align:"center",
            dataIndex: 'projectAmount',
            width: 120,
            sorter: true,
            customRender: (text) => {
              if (!text && text !== 0) return '-';
              return text.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY', minimumFractionDigits: 2 });
            }
          },
          {
            title: '开始日期',
            align:"center",
            dataIndex: 'startDate',
            width: 120,
            sorter: true
          },
          {
            title: '结束日期',
            align:"center",
            dataIndex: 'endDate',
            width: 120,
            sorter: true
          },
          {
            title: '省市区',
            align:"center",
            dataIndex: 'area',
            width: 180,
            ellipsis: true,
            customRender: (text, record) => {
              // 组合省市区显示
              let areaText = [];
              
              // 优先使用名称
              if (record.provinceName) areaText.push(record.provinceName);
              if (record.cityName && record.cityName !== '市辖区') areaText.push(record.cityName);
              if (record.areaName) areaText.push(record.areaName);
              
              // 如果没有名称，则显示编码
              if (areaText.length === 0) {
                if (record.provinceCode) areaText.push(record.provinceCode);
                if (record.cityCode) areaText.push(record.cityCode);
                if (record.areaCode) areaText.push(record.areaCode);
              }
              
              return areaText.length > 0 ? areaText.join('/') : '未设置';
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed: 'right',
            width: 150,
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 查询条件
        queryParam: {},
        url: {
          list: "/crm/project/list",
          delete: "/crm/project/delete",
          deleteBatch: "/crm/project/deleteBatch"
        },
        // 是否展开高级搜索
        toggleSearchStatus: false
      }
    },
    methods: {
      // 加载权限数据
      loadPermissionData() {
        // 获取用户权限列表
        const userAuth = JSON.parse(sessionStorage.getItem('LOGIN_USER_BUTTON_AUTH') || '[]');
        const sysAuth = JSON.parse(sessionStorage.getItem('SYS_BUTTON_AUTH') || '[]');
        
        // 合并权限数据
        this.permissionList = [];
        
        // 处理用户权限
        userAuth.forEach(auth => {
          if (typeof auth === 'string') {
            this.permissionList.push(auth);
          } else if (auth && auth.action) {
            this.permissionList.push(auth.action);
          }
        });
        
        // 处理系统权限
        sysAuth.forEach(auth => {
          if (typeof auth === 'string') {
            if (!this.permissionList.includes(auth)) {
              this.permissionList.push(auth);
            }
          } else if (auth && auth.action) {
            if (!this.permissionList.includes(auth.action)) {
              this.permissionList.push(auth.action);
            }
          }
        });
      },
      
      // 判断是否有权限
      hasPermission(permission) {
        if (!permission) return false;
        
        // 检查权限列表中是否包含指定权限
        if (this.permissionList.includes(permission)) {
          return true;
        }
        
        // 检查权限列表中是否包含以逗号分隔的多个权限
        for (let perm of this.permissionList) {
          if (perm && perm.includes(',')) {
            const perms = perm.split(',');
            if (perms.includes(permission)) {
              return true;
            }
          }
        }
        
        return false;
      },
      // 重写loadData方法，使用自定义的API调用
      loadData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        
        console.log('查询参数处理前:', JSON.stringify(params));
        
        // 格式化日期
        if (params.startDate_begin) {
          params.startDate_begin = moment(params.startDate_begin).format('YYYY-MM-DD');
        }
        if (params.startDate_end) {
          params.startDate_end = moment(params.startDate_end).format('YYYY-MM-DD');
        }
        if (params.endDate_begin) {
          params.endDate_begin = moment(params.endDate_begin).format('YYYY-MM-DD');
        }
        if (params.endDate_end) {
          params.endDate_end = moment(params.endDate_end).format('YYYY-MM-DD');
        }
        
        console.log('请求参数处理后:', JSON.stringify(params));
        
        projectList(params).then((res) => {
          console.log('API返回数据:', res);
          if (res.success) {
            // 设置数据源
            this.dataSource = res.result.records || [];
            // 设置分页信息
            this.ipagination.total = res.result.total || 0;
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      // 添加项目
      handleAdd() {
        this.$refs.modalForm.add();
        this.$refs.modalForm.title = "添加工程项目";
      },
      // 编辑项目
      handleEdit(record) {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "编辑工程项目";
      },
      // 查看项目详情
      handleDetail(record) {
        this.$refs.detailModal.show(record);
      },
      // 删除项目
      handleDelete(id) {
        projectDelete({ id: id }).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadData();
          } else {
            this.$message.warning(res.message);
          }
        });
      },
      // 批量删除
      batchDelete() {
        if (!this.selectedRowKeys.length) {
          this.$message.warning('请选择需要删除的记录');
          return;
        }
        
        let that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            projectDeleteBatch({ ids: that.selectedRowKeys.join(',') }).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      },
      // 表单提交回调
      modalFormOk() {
        this.loadData();
      },
      // 切换高级查询状态
      handleToggleSearch() {
        this.toggleSearchStatus = !this.toggleSearchStatus;
      },
      // 重写查询方法
      searchQuery() {
        console.log('执行查询，参数:', this.queryParam);
        this.loadData(1);
      },
      // 重写重置方法
      searchReset() {
        console.log('执行重置');
        this.queryParam = {};
        this.loadData(1);
      },
      // 导出Excel
      handleExportXls(fileName) {
        if(!fileName || typeof fileName != 'string'){
          fileName = '导出文件'
        }
        let param = { ...this.queryParam };
        if(this.selectedRowKeys && this.selectedRowKeys.length>0){
          param['selections'] = this.selectedRowKeys.join(",")
        }
        console.log('导出参数:', param);
        this.$message.success('导出中，请稍后');
        // 如果有导出URL，可以使用下面的代码
        // window.location.href = `${window.location.origin}/${this.url.exportXlsUrl}?${this.getUrlParam(param)}`;
      },
      // 文件导入前处理
      beforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
          this.$message.warning('文件必须小于10MB!');
          return false;
        }
        this.$message.success('导入中，请稍后');
        // 这里可以添加文件上传逻辑
        return false;
      },
      // 省份变化处理
      provinceChange(value) {
        this.queryParam.cityCode = undefined;
        this.queryParam.areaCode = undefined;
        this.areaOptions = {};
        if (value) {
          this.loadCityData(value);
        } else {
          this.cityOptions = {};
        }
      },
      // 城市变化处理
      cityChange(value) {
        this.queryParam.areaCode = undefined;
        if (value) {
          this.loadAreaData(value);
        } else {
          this.areaOptions = {};
        }
      },
      // 加载省份数据
      loadProvinceData() {
        this.provinceOptions = this.$Jpcaa['86'];
      },
      // 加载城市数据
      loadCityData(provinceCode) {
        this.cityOptions = this.$Jpcaa[provinceCode] || {};
      },
      // 加载区县数据
      loadAreaData(cityCode) {
        this.areaOptions = this.$Jpcaa[cityCode] || {};
      }
    }
  }
</script>

<style scoped>
  .ant-alert-info {
    display: flex;
    align-items: center;
  }
  
  /* 表格横向滚动样式 */
  .ant-table-wrapper {
    overflow-x: auto;
  }
  .ant-table-body {
    overflow-x: auto !important;
  }
  /* 适配小屏幕设备 */
  @media screen and (max-width: 1200px) {
    .ant-table-content {
      overflow-x: auto;
    }
  }
  
  /* 查询区域样式 */
  .table-page-search-wrapper {
    margin-bottom: 18px;
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  }
  
  .table-page-search-submitButtons {
    display: flex;
    align-items: center;
    margin-top: 24px;
  }
  
  /* 表格区域样式 */
  .card-table {
    margin-top: 16px;
  }
  
  /* 操作按钮区域样式 */
  .table-operator {
    margin-bottom: 18px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  
  .table-operator button {
    margin-bottom: 8px;
  }
  
  /* 固定列样式 */
  .ant-table-fixed-right {
    box-shadow: -6px 0 6px -4px rgba(0, 0, 0, 0.15);
  }
  
  .ant-table-tbody > tr > td.ant-table-fixed-columns-in-body {
    background-color: #fff;
  }
</style> 